package problem;

import java.util.ArrayDeque;
import java.util.Deque;

/**
 * 括号匹配算法题
 * @see <a href="https://leetcode-cn.com/problems/valid-parentheses/">20. 有效的括号</a>
 * @author RunningShrimp
 * @date 2021/5/10  18:07
 */
public class BracketMatching {
    public boolean isValid(String s) {
        if (s == null || s.length() % 2 != 0) {
            return false;
        }
        Deque<Character> deque = new ArrayDeque<>();
        boolean flag = true;
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            if (ch == '{' || ch == '[' || ch == '(') {
                deque.push(ch);
            } else {
                if (!deque.isEmpty()) {
                    char c = deque.pop();
                    if (ch - c != 2 && ch - c != 1) {
                        return false;
                    }
//                    if (ch == '}') {
//                        if (c != '{') {
//                            return false;
//                        }
//                    } else if (ch == ']') {
//                        if (c != '[') {
//                            return false;
//                        }
//                    } else if (ch == ')') {
//                        if (c != '(') {
//                            return false;
//                        }
//                    }
                }else {
                    flag = false;
                }
            }
        }

        return flag && deque.isEmpty();
    }

    public boolean isValid2(String s) {
        if (s == null || s.length() % 2 != 0) {
            return false;
        }
        //放置未配对的字符
        char[] chars = new char[s.length()];
        int count = 0;
        for (int i = 0; i < s.length(); i++) {
            chars[count] = s.charAt(i);
            //编码差为2 或者 1 累计数量--
            if (count != 0 && (chars[count] - chars[count - 1] == 2 || chars[count] - chars[count - 1] == 1)) {
                count--;
            } else {
                count++;
            }
        }
        return count == 0;
    }

    public static void main(String[] args) {
        System.out.println(new BracketMatching().isValid("[[[]"));
        System.out.println(new BracketMatching().isValid("()))"));
        System.out.println(2&1);
    }
}
